import React, { useState, useEffect } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Divider, Grid, Button } from '@material-ui/core';
import { Section, SectionAlternate } from 'components/organisms';
import { useDispatch, useSelector } from 'react-redux';
import {
  Hero,
  Main,
  VerticalTransparent,
} from './components';
import { useParams } from "react-router-dom";
import { callGetApi } from 'utils/networking';

const scrollTo = id => {
  setTimeout(() => {
    const element = document.querySelector(`#${id}`);
    if (!element) {
      return;
    }

    window.scrollTo({ left: 0, top: element.offsetTop, behavior: 'smooth' });
  }, 100);
};

const useStyles = makeStyles(theme => ({
  pagePaddingTop: {
    paddingTop: theme.spacing(3),
    [theme.breakpoints.up('md')]: {
      paddingTop: theme.spacing(5),
    },
  },
  sectionAlternate: {
    background: 'transparent',
    backgroundImage: `linear-gradient(180deg, ${theme.palette.background.paper} 40%, ${theme.palette.primary.dark} 0%)`,
  },
}));

const Podcast = () => {
  const classes = useStyles();
  let { id } = useParams();
  const dispatch = useDispatch();

  const [mPodcast, setPodcast] = useState(useSelector((state) => state.podcasts.selectedPodcast))
  const [mSeasons, setSeasons] = useState([])
  const [subscribeSettings, setSubscribeSettings] = useState(null)

  useEffect(() => {
    loadPodcastSeasons()
  }, [id]);

  const loadPodcastSeasons = async () => {
    callGetApi (`podcast/podcast_media?podcast_id=${id}`, dispatch, (data) => {
      setPodcast(data.podcast);
      setSeasons(data.podcast_seasons);
      setSubscribeSettings(data.subscription_settings);
    })
  }

  const checkSubscribable = () => {
    return subscribeSettings && subscribeSettings.subscription_items && subscribeSettings.subscription_items.length>0
  }

  return (
    <div>
      <Section className={classes.pagePaddingTop}>
        <Hero data={mPodcast} subscriable={checkSubscribable()} scrollTo={scrollTo} />
        <Section>
          <Divider />
        </Section>
        <VerticalTransparent data={mSeasons} />
        <Section>
          <Divider />
        </Section>
        { checkSubscribable() && (
          <Main id="SubscriptionSection" data={subscribeSettings} />
        )}
      </Section>
    </div>
  );
};

export default Podcast;
